package com.kclm.se.nio;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelv1 {

	public static void main(String[] args) {
		String path = "files/nio-data.txt";
		//
		try(FileInputStream fis = new FileInputStream(path);
				FileChannel fc = fis.getChannel()) {
			// 创建 Buffer
			ByteBuffer buffer = ByteBuffer.allocate(3);
			//
			int len = -1;
			while((len = fc.read(buffer)) != -1) { //finished. position = 3
				System.out.println("\n本次读到的字节数："+len);
				//反转 buffer
				buffer.flip(); //做了两件事：1. limit = position; 2. position = 0;
				//把buffer中的数据取出来
				while(buffer.hasRemaining()) {
					//每次读一个字节
					System.out.print((char)buffer.get()); //position++
					Thread.sleep(500);
				}
				//清空缓存
				buffer.clear();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
